package com.cn.codebrush.链表;

public class No21合并两个有序链表 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        ListNode node1 = new ListNode(2);
        ListNode node2 = new ListNode(4);
        l1.next = node1;
        node1.next=node2;


        ListNode l2 = new ListNode(1);
        ListNode node_1 = new ListNode(3);
        ListNode node_2 = new ListNode(4);

        l2.next = node_1;
        node_1.next=node_2;

        System.out.println(mergeTwoLists(l1,l2));
    }

    public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode temp = new ListNode();
        ListNode res = temp;

        while(list1 != null && list2 != null){
            int val1 = list1.val;
            int val2 = list2.val;
            int val = val1>=val2?val2:val1;
            temp.next = new ListNode(val);
            temp = temp.next;
            if(val1>=val2){
                list2=list2.next;
            }
            if(val2>val1){
                list1=list1.next;
            }
        }
        if(list1 == null){
            temp.next = list2;
        }
        if(list2 == null){
            temp.next = list1;
        }

        return res.next;
    }
}
